/**
 * Copyright (C), 2015-2018, XXX有限公司
 * FileName: MailServiceImpl
 * Author:   zhouheng
 * Date:     2018/7/29 13:02
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.hengby.hengcrud.modular.mail.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hengby.hengcrud.modular.mail.mapper.MailMapper;
import com.hengby.hengcrud.modular.mail.model.Email;
import com.hengby.hengcrud.modular.mail.model.OaEmail;
import com.hengby.hengcrud.modular.mail.service.IMailService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.thymeleaf.spring4.SpringTemplateEngine;

import javax.mail.internet.MimeMessage;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br> 
 * 〈〉
 *
 * @author zhouheng
 * @create 2018/7/29
 * @since 1.0.0
 */

@Service
public class MailServiceImpl extends ServiceImpl<MailMapper,OaEmail> implements IMailService{

    @Autowired
    private JavaMailSender mailSender;//执行者

    @Autowired
    public Configuration configuration;//freemarker

    @Autowired
    private SpringTemplateEngine templateEngine;//thymeleaf

    @Value("${spring.mail.username}")
    public String USER_NAME;//发送者

    @Value("${heng_crud.servlet-path}")
    public String PATH;//发送者

    /**
     * @description: 模版发送 freemarker
     * @date: 2018/7/29 14:31
     * @author:zhouheng
     */
    @Override
    public void sendFreemarker(@Valid Email mail) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);

        helper.setFrom(USER_NAME);
        helper.setTo(mail.getEmail());
        helper.setSubject(mail.getSubject());
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("mail", mail);
        model.put("path", PATH);
        Template template = configuration.getTemplate(mail.getTemplate()+".flt");
        String text = FreeMarkerTemplateUtils.processTemplateIntoString(
                template, model);
        helper.setText(text, true);
        mailSender.send(message);
        mail.setContent(text);
        OaEmail oaEmail = new OaEmail(mail);

        this.baseMapper.insert(oaEmail);
    }

    @Override
    public List<Map<String, Object>> findAll() {
        return this.baseMapper.selectMaps(new EntityWrapper<>());
    }
}